//
//  ZTUser.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/30.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "ZTUser.h"
#import "MQTTCoverTool.h"
#import "objc/runtime.h"
#import "GlobalConst.h"
@implementation ZTUser

+ (ZTUser *)userWithTelNum:(NSString*)telNum
                      pawd:(NSString *)pawd
{
    ZTUser *user = [[ZTUser alloc]init];
    user.apsn = kZTCloudGatewayApsn;
    NSInteger newLuid = [MQTTCoverTool mobileToLuid:telNum];
    user.luid = newLuid;
    user.m_strTel = telNum;
    user.m_strPwd = pawd;
    user.currentBindApsn = 0;
    return user;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int ivarsCont = 0;
    Ivar* ivars =  class_copyIvarList([self class], &ivarsCont);
    for (int i = 0; i < ivarsCont; i++) {
        Ivar var = ivars[i];
        const char *name = ivar_getName(var);
        NSString *key  = [NSString stringWithUTF8String:name];
        id value = [self valueForKey:key];
        [aCoder encodeObject:value forKey:key];
    }
    free(ivars);
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        Class cls = [self class];
        unsigned int ivarsCnt = 0;
        //获取成员变量,ivarsCnt就是成员变量
        Ivar * ivars = class_copyIvarList(cls, &ivarsCnt);
        //遍历成员变量,每个成员便令都是Ivar 类型的结构体
        for (int i = 0 ; i < ivarsCnt; i++) {
            //获取变量名
            Ivar var = ivars[i];
            const  char * name = ivar_getName(var);
            NSString * key = [NSString stringWithUTF8String:name];
            //获取变量值,解档出来的值
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
        free(ivars);
    }
    return self;
}
- (BOOL)alreadyBindGateway
{
    return self.currentBindApsn != 0;
}
- (void)archiver
{
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"ZTUser.archiver"];
    [NSKeyedArchiver archiveRootObject:self toFile:path];
}
+ (ZTUser *)unarchiver
{
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"ZTUser.archiver"];;
    ZTUser *user = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    return user;
}
@end
